package util

import (
	"time"
	"encoding/json"
	"crypto/des"
	"bytes"
	"crypto/hmac"
	"encoding/base64"
	"crypto/sha256"
	"encoding/hex"
)

func desECBEncrypt(data, key []byte) string {
    block, err := des.NewCipher(key)
    if err != nil {
		return ""
    }

    bs := block.BlockSize()
    data = pkcs5Padding(data, bs)
    if len(data) % bs != 0 {
		return ""
    }

    out := make([]byte, len(data))
    dst := out
    for len(data) > 0 {
        block.Encrypt(dst, data[:bs])
        data = data[bs:]
        dst = dst[bs:]
	}

    return base64.StdEncoding.EncodeToString(out)
}

func pkcs5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext) % blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)

	return append(ciphertext, padtext...)
}

func getEncorypt(jsonString string) string{
	key := []byte(KEY[:8])
	encryptByDESModeEBC := desECBEncrypt([]byte(jsonString), key)

	return encryptByDESModeEBC
}

func computeHmac256(message string, secret string) string {
    h := hmac.New(sha256.New, []byte(secret))
    h.Write([]byte(message))

	sha := hex.EncodeToString(h.Sum(nil))
    return sha
}

func getSignature(encorypt , timestamp, version string) string {
	sign_str := encorypt + "&" + MERID + "&" + timestamp + "&" + version
	return computeHmac256(sign_str, KEY)
}

func GetParams(jsonString string) *bytes.Buffer{
	timestamp := time.Now().Format("20060102150405")
	version := "v2.2"
	encorypt := getEncorypt(jsonString)
	signature := getSignature(encorypt, timestamp, version)
	postBody, _ := json.Marshal(map[string]string{
		"mer_id": MERID,
		"version": version,
        "timestamp": timestamp,
        "data": encorypt,
        "signature": signature,
	})

	responseBody := bytes.NewBuffer(postBody)

	return responseBody
}